package com.controller.sys;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.Result;
import com.entity.sys.UserRole;
import com.service.sys.UserRoleService;
import com.service.sys.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author clay
 * @since 2022-02-15
 */
@Api("UserRoleController")
@RestController
@RequestMapping("/sys/userRole")
public class UserRoleController {

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private UserService userService;

    @ApiOperation("通过用户id查询拥有的权限")
    @GetMapping("/getRoleByUserId/{id}")
    public Result getRoleByUserId(@PathVariable String id) {
        return Result.success(userService.getRoles(id));
    }

    /**
     * 这个接口后期需要加上权限不相容功能，即有的角色不能在同一个人身上分配
     * @return
     */
    @ApiOperation("分配权限")
    @PostMapping("/assignRole/{userId}")
    @Transactional(rollbackFor = RuntimeException.class)
    public Result assignRole(@PathVariable String userId, @RequestBody List<UserRole> userRoles) {
        try {
            userRoleService.remove(new QueryWrapper<UserRole>().eq(
                    "user_id", userId
            ));
            userRoleService.saveBatch(userRoles);
            return Result.success();
        } catch (RuntimeException e) {
            return Result.fail("分配权限失败!");
        }
    }
}
